package net.sahv.bdyz.interceptor;

import java.net.URLEncoder;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author 作者 : 任凯伟
 * @date 创建时间：2016年9月1日 上午9:48:13
 * @version 1.0
 * @see 单点登录拦截
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
	/** 重定向视图名称前缀 */
	private static final String REDIRECT_VIEW_NAME_PREFIX = "redirect:";

	/** "重定向URL"参数名称 */
	private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl";

	/** "会员"属性名称 */
	private static final String MEMBER_ATTRIBUTE_NAME = "member";

	/** 默认登录URL */
	private static final String DEFAULT_LOGIN_URL = "/bdyz/web/member/login";

	/** 登录URL */
	private String loginUrl = DEFAULT_LOGIN_URL;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		HashMap hUserName = (HashMap) session.getAttribute("hUserName");
		String telphone = (String) session.getAttribute("telphone");
		String stelphone = (String) hUserName.get(session.getId());
		if (hUserName != null && hUserName.containsValue(telphone) && telphone != null && telphone.equals(stelphone)) {
			return true;
		} else if (hUserName != null && !hUserName.containsValue(telphone)) {
			return true;
		} else {
			String requestType = request.getHeader("X-Requested-With");
			if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
				response.addHeader("loginStatus", "accessDenied");
				response.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			} else {
				if (request.getMethod().equalsIgnoreCase("GET")) {
					String redirectUrl = request.getQueryString() != null
							? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI();
					response.sendRedirect(
							loginUrl + "?" + REDIRECT_URL_PARAMETER_NAME + "=" + URLEncoder.encode(redirectUrl));
				} else {
					response.sendRedirect(loginUrl);
				}
				return false;
			}
		}
	}

	/**
	 * 获取登录URL
	 * 
	 * @return 登录URL
	 */
	public String getLoginUrl() {
		return loginUrl;
	}

	/**
	 * 设置登录URL
	 * 
	 * @param loginUrl
	 *            登录URL
	 */
	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}
}
 